package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.zzyl.nursing.util.CodeGenerator;

/**
 * 入住Service业务层处理
 *
 * @author JBY
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private BedServiceImpl bedService;

    @Autowired
    private ContractServiceImpl contractService;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    @Transactional(readOnly = true)
    public CheckInDetailVo selectCheckInById(Long id) {
        // 1. 通过入住ID获取全部checkIn
        CheckIn checkIn = this.getById(id);

        // 2. 从checkin表获取老人ID, 通过老人ID查找Elder表
        Long elderId = checkIn.getElderId();
        Elder elder = elderService.getById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // 2.2 计算老人年龄
        String birthday = elder.getBirthday();
        String now = LocalDate.now().toString();
        int age = LocalDate.parse(birthday).until(LocalDate.parse(now)).getYears();
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder, checkInElderVo);

        // 3. 从入住表获取remark, 家属JSON转为对象, 存入集合
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        // 4. 通过checkInId获取checkInConfig
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        // 5. 通过老人ID获取合同
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractService.getOne(contractWrapper);

        // 6. 封装
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo(checkInElderVo, elderFamilyVoList, checkInConfigVo, contract);
        return checkInDetailVo;
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkInApplyDto 入住
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {   //0. 先获取需要的数据
        //入住老人信息
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        //家人信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        //入住配置
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        //签约办理信息
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();

        //1. 验证老人是否已入住
        String idCardNo = checkInElderDto.getIdCardNo();
        //如果身份证号重复 则说明老人之前办理过入住 然后获取status修改状态
        LambdaQueryWrapper<Elder> checkInElderDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        checkInElderDtoLambdaQueryWrapper.eq(Elder::getIdCardNo, idCardNo)
                .in(Elder::getStatus, 1, 2, 4);
        Elder one = elderService.getOne(checkInElderDtoLambdaQueryWrapper);
        //判断数据库中是否有老人的ID和状态情况, 如果已存在则返回错误.
        if (ObjectUtil.isNotNull(one)) {
            throw new BaseException("该用户已存在!!!");
        }

        //2. 更新床位状态为已入住
        //先根据ID获取数据库中的Bed对象
        Bed bed = bedService.selectBedById(checkInConfigDto.getBedId());
        //修改状态为1 表示已入住
        bed.setBedStatus(1);
        //update Bed set status = 1 where status = 0 and id = #{bedId}
        boolean update = bedService.update(bed, new LambdaQueryWrapper<Bed>().eq(Bed::getId, bed.getId()).eq(Bed::getBedStatus, 0));
        //对更新情况进行判断, 如果更新失败则返回错误.
        if (!update) {
            throw new BaseException("该床位已被选用!!!");
        }

        //3. 新增(首次入住)或者更新(老玩家回归)老人
        Elder elder = updateOrAddElder(checkInElderDto, bed);
        //4. 新增签约办理
        insertContract(elder, checkInContractDto, checkInConfigDto);
        //5. 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, elderFamilyDtoList, checkInConfigDto);
        //6. 新增入住配置
        insertCheckInConfig(checkIn, checkInConfigDto);
    }

    /**
     * 新增入住配置
     *
     * @param: CheckIn checkIn
     * @param: CheckInConfigDto checkInConfigDto
     * @return: void
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        // 创建入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        // 插入入住配置
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param: Elder elder
     * @param: List<ElderFamilyDto> elderFamilyDtoList
     * @param: CheckInConfigDto checkInConfigDto
     * @return:
     */
    private CheckIn insertCheckIn(Elder elder, List<ElderFamilyDto> elderFamilyDtoList, CheckInConfigDto checkInConfigDto) {
        // 创建入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInConfigDto, checkIn, "id");
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkIn.setBedNumber(elder.getBedNumber());
        // 插入入住信息
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param: Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto
     * @return: void
     */
    private void insertContract(Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {
        // 创建签约办理
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(elder.getId().intValue());
        contract.setContractName(checkInContractDto.getContractName());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contract.setSignDate(checkInContractDto.getSignDate());
        // 插入签约办理
        contractService.save(contract);
    }

    /**
     * 新增或更新老人
     *
     * @param: CheckInElderDto checkInElderDto, Bed bed
     * @return: void
     */
    private Elder updateOrAddElder(CheckInElderDto checkInElderDto, Bed bed) {
        // 1. 准备老人对象 复制一份 用于更新或新增
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        // 1.1 将Bed的数据设置给老人对象
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        // 2. 从数据库中根据身份证号查找老人 判断老人是否存在
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        // 2.2 数据库中的老人对象, 仅用于判断
        Elder elderDb = elderService.getOne(elderWrapper);
        if (ObjectUtil.isNotNull(elderDb)) {
            // 3. 如果存在则更新 从数据库中获取已存在的老人ID, 赋值给new的elder对象
            elder.setId(elderDb.getId());
            elderService.updateById(elder);
            return elder;
        } else {
            // 4. 不存在则新增
            elderService.save(elder);
            return elder;
        }
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }
}
